var path = require('path');
var webpack = require('webpack');
var dev=process.env.NODE_ENV==='dev';
var glob = require("glob");
var config = require(`./config.${process.env.NODE_ENV}.json`);

var files = glob.sync("./static/**/*.entry.js");

function entry(name){
    if(dev){
        return ['webpack-dev-server/client?http://localhost:16001',
                'webpack/hot/only-dev-server',
                name];
    }
    return name;
}

function entries(files){
    var ret={};
    files.map((val) => {
        var name=val.slice('./static/'.length, 0 - '.entry.js'.length);
        ret[name]=entry(val)
    });
    return ret;
}

function js_ugly(config, ugly){
    if(ugly===true || ugly==='true'){
        config.plugins.push(new webpack.optimize.UglifyJsPlugin({sourceMap: false,compress:{warnings:false},output:{comments:false}}));
    }
}
//获得所有style 下css
var cssFiles = glob.sync("./static/**/style/*.scss");
function getCssObject(cssFiles){
    var cssObject = {};
    cssFiles.forEach((val)=>{
        var name=val.replace(/(\.)?((\/||\/\/)?[\w-]*(\/||\/\/)?)*(([\w-]*).scss)/g,"$2");
        cssObject[name+".scss"] = __dirname + '/dist/static/style/'+name+'.css';

    });
    return cssObject
}

var webpackConfig = {
    resolve:{
        extensions:['', '.js', '.jsx'],
        alias: Object.assign({},{
            "antd.css":__dirname + "/node_modules/antd/dist/antd.min.css",
             "ckeditor":__dirname + "/static/plugins/ckeditor/ckeditor.js"
        },getCssObject(cssFiles))
    },

    entry: entries(files),
    output: {
        path: __dirname+ '/dist/static',
        filename: '[name].js',
        publicPath: '/static/'
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            {
                test: /.jsx?$/,
                loaders: ['react-hot', 'babel?{"presets": ["es2015", "react", "stage-0", "stage-3"], "plugins": [ "transform-runtime", "syntax-async-functions", "transform-function-bind"]}'],
                exclude: /node_modules/
            },
            {
                test: /\.scss$/,
                exclude: path.resolve(__dirname, 'static/style'),
                loader: "style!css?modules&localIdentName=[name]__[local]!sass?includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")

            },{
                test: /\.scss$/,
                include: path.resolve(__dirname, 'static/style'),
                loader: 'style!css!sass?sourceMap=true'
            }

        ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    devServer:{
        proxy: {
            "*": `http://localhost:${config.server.port}`
        },
        port:16001,
        publicPath: '/static/',
        hot: true,
        historyApiFallback: true
    }
};
if(process.env.NODE_ENV == 'dev'){
    webpackConfig.devtool= 'eval'
}
module.exports =webpackConfig;

js_ugly(module.exports,!dev);
